package com.leyou.search.mq;



import com.leyou.api.controller.FeignController;
import com.leyou.pojo.dto.SpuDto;
import com.leyou.search.Reposity.GoodsRepository;
import com.leyou.search.entity.Goods;
import com.leyou.search.service.SearchService;
import com.leyou.search.service.impl.SearchServiceImpl;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.ITEM_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.SEARCH_ITEM_DOWN;
import static com.leyou.common.constants.MQConstants.QueueConstants.SEARCH_ITEM_UP;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_DOWN_KEY;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.ITEM_UP_KEY;
@Component
public class ReceiveRabbit {


    @Autowired
    private GoodsRepository repository;
    @Autowired
    private FeignController feignController;
    @Autowired
    private SearchServiceImpl searchServiceImpl;
    @RabbitListener(bindings =@QueueBinding(

            value = @Queue(name = SEARCH_ITEM_UP,durable = "true"),
            exchange = @Exchange(name = ITEM_EXCHANGE_NAME, durable = "true", type = ExchangeTypes.TOPIC),
            key = {ITEM_UP_KEY})
    )
    //上架，新增
    public void receiveRabbitUp(Long id){
        //判断数据为空
        if(id==null){
            return;
        }
        //查询spu
        SpuDto spuDto = feignController.querySkuAndSpuAndSpuDetail(id);
        //装换成good
        Goods goods = searchServiceImpl.conserve(spuDto);
        //新增
        repository.save(goods);
//        System.out.println("hah");

    }

    @RabbitListener(bindings =@QueueBinding(

            value = @Queue(name = SEARCH_ITEM_DOWN,durable = "true"),
            exchange = @Exchange(name = ITEM_EXCHANGE_NAME, durable = "true", type = ExchangeTypes.TOPIC),
            key = {ITEM_DOWN_KEY})
    )
    //下架，删除
    public void receiveRabbitDown(Long id){
        //判断数据为空
        if(id==null){
            return;
        }
       repository.deleteById(id);
    }
}
